package com.i2works.smartluolong.web.service.company.impl;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.i2works.smartluolong.utils.base.*;
import com.i2works.smartluolong.utils.basecommon.BaseCommonServiceImpl;
import com.i2works.smartluolong.utils.exception.DAOException;
import com.i2works.smartluolong.utils.exception.ServiceException;
import com.i2works.smartluolong.web.dal.company.dao.ICompanyApplyDAO;
import com.i2works.smartluolong.web.dal.company.dao.ICompanyApplyMemberDAO;
import com.i2works.smartluolong.web.entity.cart.CartReceiveDO;
import com.i2works.smartluolong.web.entity.company.*;
import com.i2works.smartluolong.web.entity.flow.FlowInfoDO;
import com.i2works.smartluolong.web.entity.flow.FlowInfoQuery;
import com.i2works.smartluolong.web.entity.flow.FlowProcessDO;
import com.i2works.smartluolong.web.service.cart.ICartReceiveService;
import com.i2works.smartluolong.web.service.company.ICompanyApplyImagesService;
import com.i2works.smartluolong.web.service.company.ICompanyApplyService;
import com.i2works.smartluolong.web.service.flow.IFlowInfoService;
import com.i2works.smartluolong.web.service.flow.IFlowProcessService;
import com.xiaoleilu.hutool.util.CollectionUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * 工商申请 - 基础业务实现类
 *
 * @author Liu Yutao <koal@vip.qq.com>
 * @date 2018/3/14 16:42
 */

@Service("companyApplyService")
public class CompanyApplyServiceImpl extends BaseCommonServiceImpl<CompanyApplyQuery, CompanyApplyDO> implements ICompanyApplyService {


    private final ICompanyApplyDAO companyApplyDAO;
    private final ICompanyApplyImagesService companyApplyImagesService;
    private final ICompanyApplyMemberDAO companyApplyMemberDAO;

    private final IFlowInfoService flowInfoService;
    private final IFlowProcessService flowProcessService;
    private final ICartReceiveService cartReceiveService;



    @Autowired
    public CompanyApplyServiceImpl(ICompanyApplyDAO companyApplyDAO, ICompanyApplyImagesService companyApplyImagesService,ICompanyApplyMemberDAO companyApplyMemberDAO, IFlowInfoService flowInfoService, IFlowProcessService flowProcessService, ICartReceiveService cartReceiveService) {
        this.companyApplyDAO = companyApplyDAO;
        this.companyApplyImagesService = companyApplyImagesService;
        this.companyApplyMemberDAO = companyApplyMemberDAO;
        this.flowInfoService = flowInfoService;
        this.flowProcessService = flowProcessService;
        this.cartReceiveService = cartReceiveService;
    }

    /**
     * 添加工商申请
     */
    @Override
    @Transactional(rollbackFor = ServiceException.class)
    public void saveOrUpdate(CompanyApplyDO companyApplyDO) throws ServiceException {
        String flowInfoMessage;
        try {
            if (companyApplyDO.getId() != null) {
                companyApplyDAO.update(companyApplyDO);
                flowInfoMessage = "用户《" + companyApplyDO.getUpdateName() + "》重提申请";
            } else {
                companyApplyDO.setCreateName(companyApplyDO.getUpdateName());
                companyApplyDAO.save(companyApplyDO);
                flowInfoMessage = "用户《" + companyApplyDO.getUpdateName() + "》新增申请";
            }
            //证照处理
            List<String> imagesList = companyApplyDO.getCompanyImagesList();
            if (CollectionUtil.isNotEmpty(imagesList)) {
                //删除图片
                companyApplyImagesService.delete(companyApplyDO.getId());
                //添加图片
                for (String images : imagesList) {
                    CompanyApplyImagesDO imagesDO = new CompanyApplyImagesDO();
                    imagesDO.setApplyId(companyApplyDO.getId());
                    imagesDO.setImg(images);
                    imagesDO.setUpdateName(companyApplyDO.getUpdateName());
                    imagesDO.setCreateName(companyApplyDO.getCreateName());
                    companyApplyImagesService.save(imagesDO);
                }
            }
            //添加工作流
            FlowInfoDO flowInfoDO = new FlowInfoDO();
            flowInfoDO.setUserId(companyApplyDO.getUserId());
            flowInfoDO.setItemStatus(CompanyStatusEnum.STATUS_0.getKey());
            flowInfoDO.setItemId(companyApplyDO.getId());
            flowInfoDO.setComplete(0);
            flowInfoDO.setItemName(companyApplyDO.getCompanyName() + "-" + FlowItemTypeEnum.COMPANY_APPLY.getValue());
            flowInfoDO.setItemType(FlowItemTypeEnum.COMPANY_APPLY.getKey());
            flowInfoDO.setMessage(flowInfoMessage);
            flowInfoDO.setUpdateName(companyApplyDO.getUpdateName());
            flowInfoDO.setCreateName(companyApplyDO.getCreateName());
            flowInfoService.save(flowInfoDO);
        } catch (DAOException e) {
            throw new ServiceException(e);
        }
    }

    @Override
    public Map<String, Object> getApplyDetail(Integer applyId) throws ServiceException {
        Map<String, Object> map = Maps.newHashMap();
        try {
            //查询详情
            CompanyApplyQuery applyQuery = new CompanyApplyQuery();
            applyQuery.setId(applyId);
            CompanyApplyDO companyApply = companyApplyDAO.query(applyQuery);
            if (null != companyApply) {
                map.put("companyApply", companyApply);
                String[] companyBrandOptionalList = StringUtils.split(companyApply.getCompanyBrandOptional(), ",");
                map.put("companyBrandOptionalList", companyBrandOptionalList);
                //查询股东
                CompanyApplyMemberQuery memberQuery = new CompanyApplyMemberQuery();
                memberQuery.setApplyId(companyApply.getId());
                memberQuery.setRole(CompanyMemberRoleEnum.ROLE_1.getKey());
                memberQuery.setStatus(GlobalConstant.status.TRUE);
                memberQuery.setLimit(100L);
                List<CompanyApplyMemberDO> shareholderList = companyApplyMemberDAO.queryShareHolderList(memberQuery);
                map.put("shareholderList", shareholderList);
                //查询其他人员
                memberQuery.setRole(CompanyMemberRoleEnum.ROLE_0.getKey());
                List<CompanyApplyMemberDO> memberList = companyApplyMemberDAO.queryList(memberQuery);
                map.put("memberList", memberList);
                //查询资料图片
                CompanyApplyImagesQuery imagesQuery = new CompanyApplyImagesQuery();
                imagesQuery.setApplyId(companyApply.getId());
                List<CompanyApplyImagesDO> imagesList = companyApplyImagesService.queryList(imagesQuery);
                map.put("imagesList", imagesList);
            }
        } catch (Exception e) {
            throw new ServiceException(e);
        }
        return map;
    }

    /**
     * 获取审核人员可管理的申请列表
     */
    @Override
    public List<CompanyApplyDO> queryListByAuditor(CompanyApplyQuery query) throws ServiceException {
        try {
            return companyApplyDAO.queryListByAuditor(query);
        } catch (DAOException e) {
            throw new ServiceException(e);
        }
    }

    /**
     * 获取审核人员可管理的申请列表统计
     */
    @Override
    public Integer queryCountByAuditor(CompanyApplyQuery query) throws ServiceException {
        try {
            return companyApplyDAO.queryCountByAuditor(query);
        } catch (DAOException e) {
            throw new ServiceException(e);
        }
    }


    /**
     * 更新申请状态
     *
     * @param companyApplyDO 申请实体
     * @param auditorId      审核人员ID
     * @param isClaim        是否认领状态
     */
    @Override
    @Transactional(rollbackFor = ServiceException.class)
    public void updateApplyStatus(CompanyApplyDO companyApplyDO, Integer auditorId, Boolean isClaim) throws ServiceException {
        try {
            //更新申请表
            companyApplyDAO.update(companyApplyDO);
            //新增流程记录
            FlowInfoQuery infoQuery = new FlowInfoQuery();
            infoQuery.setItemId(companyApplyDO.getId());
            infoQuery.setItemType(FlowItemTypeEnum.COMPANY_APPLY.getKey());
            FlowInfoDO infoDO = flowInfoService.query(infoQuery);
            infoDO.setItemStatus(companyApplyDO.getApplyStatus());
            //如果是认领（待审核），就设置审核人ID为空(-1，mybatis自行处理)
            if (isClaim) {
                infoDO.setAuditorId(FlowConstant.base.NULL);
            } else {
                infoDO.setAuditorId(auditorId);
            }
            //如果状态是4（核准通过），设置状态为已完成
            if (companyApplyDO.getApplyStatus().equals(CompanyStatusEnum.STATUS_4.getKey())) {
                infoDO.setComplete(FlowConstant.complete.TRUE);
                //添加签发认领表信息
                CartReceiveDO cartReceiveDO = new CartReceiveDO();
                cartReceiveDO.setItemId(companyApplyDO.getId());
                cartReceiveDO.setItemName(companyApplyDO.getCompanyName());
                cartReceiveDO.setItemUserId(companyApplyDO.getUserId());
                cartReceiveDO.setItemType(FlowItemTypeEnum.COMPANY_APPLY.getKey());
                cartReceiveDO.setStatus(GlobalConstant.status.TRUE);
                cartReceiveDO.setUpdateName(companyApplyDO.getUpdateName());
                cartReceiveDO.setCreateName(companyApplyDO.getUpdateName());
                cartReceiveService.save(cartReceiveDO);
            }
            infoDO.setUpdateName(companyApplyDO.getUpdateName());
            infoDO.setUpdateTime(companyApplyDO.getUpdateTime());
            flowInfoService.update(infoDO);
            //插入记录表
            FlowProcessDO flowProcessDO = new FlowProcessDO();
            flowProcessDO.setAuditorId(auditorId);
            flowProcessDO.setItemId(companyApplyDO.getId());
            flowProcessDO.setItemType(FlowItemTypeEnum.COMPANY_APPLY.getKey());
            // 公司申请
            flowProcessDO.setItemTitle(companyApplyDO.getCompanyName() + "-" + FlowItemTypeEnum.COMPANY_APPLY.getValue());
            flowProcessDO.setMessage(companyApplyDO.getAuditMessage());
            flowProcessDO.setAuditStatus(companyApplyDO.getApplyStatus());
            flowProcessDO.setUpdateName(companyApplyDO.getUpdateName());
            flowProcessDO.setCreateName(companyApplyDO.getUpdateName());
            flowProcessService.save(flowProcessDO);
        } catch (DAOException e) {
            throw new ServiceException(e);
        }
    }


    /**
     * 查询证件领取人的手机号（法人和代办人）
     */
    @Override
    public String queryPhoneByCertHolder(CompanyApplyQuery query) throws ServiceException {
        try {
            return companyApplyDAO.queryPhoneByCertHolder(query);
        } catch (DAOException e) {
            throw new ServiceException(e);
        }
    }

    /**
     * 查询证件领取人的身份证号（法人和代办人）
     */
    @Override
    public String queryIdcardByCertHolder(CompanyApplyQuery query) throws ServiceException {
        try {
            return companyApplyDAO.queryIdcardByCertHolder(query);
        } catch (DAOException e) {
            throw new ServiceException(e);
        }
    }

    /**
     * 查询报表列表
     */
    @Override
    public List<JSONObject> queryReportList(CompanyApplyQuery query) throws ServiceException {
        try {
            return companyApplyDAO.queryReportList(query);
        } catch (DAOException e) {
            throw new ServiceException(e);
        }
    }
}
